package TestHeap;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-05-23
 * Time: 11:07
 */
public class TestHeap {
    public int[] elem;
    public int usedSize;
    public TestHeap(){
        this.elem = new int[10];
    }
    public void initElem(int[] array){
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }

    }
    public void createBigHeap(){
        for (int parent = (usedSize-1-1)/2; parent >=0 ; parent--) {
            shiftDown(parent,usedSize);
        }
    }
    public void shiftDown(int parent , int len){
        int child = 2*parent+1;
        while(child < len){
            if( child+1 < usedSize && elem[child] < elem[child+1]){
                child++;
            }
            if(elem[child] > elem[parent]){
                swap(child,parent);
                parent = child ;
                child = parent*2 +1;
            }else{
                break;
            }
        }
    }
    private void swap(int i,int j){
        int tmp =elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }
    public int poll(){
        int val = elem[0];
        swap(0,usedSize-1);
        usedSize--;
        shiftDown(0,usedSize);
        return val;
    }
    public void offer(int val){
        if(isFull()){
            elem = Arrays.copyOf(elem, elem.length*2);
        }
        elem[usedSize] = val ;
        usedSize++;
        shiftUp(usedSize-1);
    }
    public boolean isFull(){
        return usedSize == elem.length;
    }

public void shiftUp(int child){
        int parent = (child-1)/2;
        while(child > 0){
            if(elem[parent] < elem[child]){
                swap(parent,child);
                child = parent ;
                parent = (child-1)/2;
            }else{
                break;
            }
        }
}



class Img implements Comparator<Integer>{
    @Override
    public int compare(Integer o1, Integer o2) {
        return o2 - o1;
    }
}


    public int[] smallestK(int[] arr, int k) {
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new Img());
        for (int i = 0; i < k; i++) {
            priorityQueue.offer(arr[i]);
        }
        for (int i = k; i < arr.length; i++) {
            int tmp = arr[0];
            if(arr[i] < tmp){
                priorityQueue.poll();
                priorityQueue.offer(arr[i]);
            }
        }
        int[] array = new int[k];
        for (int i = 0; i < k; i++) {
            array[i] = priorityQueue.poll();
            
        }
return array;
    }

}
